package com.ly.system.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.aliyuncs.ram.model.v20150501.CreateUserResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ly.config.handler.BusinessException;
import com.ly.config.response.ResultCode;
import com.ly.system.entity.TbDepartment;
import com.ly.system.entity.TbUser;
import com.ly.system.enums.UserStatusEnum;
import com.ly.system.enums.UserTypeEnum;
import com.ly.system.mapper.TbDepartmentMapper;
import com.ly.system.mapper.TbUserMapper;
import com.ly.system.service.TbUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author jiangzhu
 * @since 2020-10-27
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {

    @Resource
    private  TbUserMapper tbUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Resource
    private TbDepartmentMapper tbDepartmentMapper;
    @Override
    public IPage<TbUser> findUserPage(Page<TbUser> page, QueryWrapper<TbUser> queryWrapper) {
        return tbUserMapper.findUserPage(page,queryWrapper);
    }

    @Override
    public void updUser(TbUser user) {
        String username = user.getUsername();
        Long departmentId = user.getDepartmentId();
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Integer count = this.baseMapper.selectCount(wrapper);

        TbDepartment department =tbDepartmentMapper.selectById(departmentId);

        String salt= UUID.randomUUID().toString().substring(0,32);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setModifiedTime(new Date());
        user.setCreateTime(new Date());
        //设置盐值  在这里其实已经没有意义了,因为spring security加密的密码默认已经提供了盐值
        user.setSalt(salt);
        //添加的用户默认是普通用户
        user.setType(UserTypeEnum.SYSTEM_USER.getTypeCode());
        //添加的用户默认启用
        user.setStatus(UserStatusEnum.AVAILABLE.getStatusCode());
        this.baseMapper.updateById(user);
    }



    @Override
    public void addUser(TbUser user) {
        String username = user.getUsername();
        Long departmentId = user.getDepartmentId();
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Integer count = this.baseMapper.selectCount(wrapper);
        if(count!=0){
            //账号已经存在
            throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }
        TbDepartment department =tbDepartmentMapper.selectById(departmentId);
        if(department==null){
            throw new BusinessException(ResultCode.DEPARTMENT_NOT_EXIST.getCode(),
                    ResultCode.DEPARTMENT_NOT_EXIST.getMessage());
        }
        String salt= UUID.randomUUID().toString().substring(0,32);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setModifiedTime(new Date());
        user.setCreateTime(new Date());
        //设置盐值  在这里其实已经没有意义了,因为spring security加密的密码默认已经提供了盐值
        user.setSalt(salt);
        //添加的用户默认是普通用户
        user.setType(UserTypeEnum.SYSTEM_USER.getTypeCode());
        //添加的用户默认启用
        user.setStatus(UserStatusEnum.AVAILABLE.getStatusCode());
        this.baseMapper.insert(user);
    }

    @Override
    public void exportUserExcel(HttpServletResponse response, List<TbUser> users) throws IOException {

        //----- 写入excel文件
        String exportFileName = "TbUserInfo.xlsx";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        EasyExcel.write(response.getOutputStream(), TbUser.class)
                .sheet("用户信息")
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(users);
    }

    @Override
    public void updatestatus(Integer status,Integer id){
        tbUserMapper.updatestatus(status,id);
    }
}
